require("Models/Player")

local EntityManagerClass = class()
EntityManager = EntityManagerClass.new()

function EntityManagerClass:Init()
    self.Entitys = {}
    self.PlayerID = nil
end

function EntityManagerClass:GetEntity(ID)
    return self.Entitys[ID]
end

function EntityManagerClass:CreateEntity(Mail, IsPlayer)
    if self.Entitys[Mail] ~= nil then
        print("实体已存在", Mail)
        return self.Entitys[Mail]
    end
    local player = PlayerClass.new()
    self.Entitys[Mail] = player
    if IsPlayer == true then
        self.PlayerID = Mail
    end
    return player
end

function EntityManagerClass:CreateEntitys(MsgPlayers)
    for key, value in ipairs(MsgPlayers) do
        player = self.Entitys[value.mail]
        if player == nil then
            player = self:CreateEntity(value.mail)
            player.Mail = value.mail
            player.RoomID = value.roomid
            player.Name = value.name
            player.Score = value.score
            player.CellTypeID = value.celltypeid
            player.CurrentCell = Map:GetCell(value.currentCell)

            player:CreateCharacter()

            player.Manors = Map:SetManors(value.manors)
            player.Tracks = Map:SetTracks(value.tracks)
        end
    end
end

function EntityManagerClass:GetPlayer()
    return self.Entitys[self.PlayerID]
end

function EntityManagerClass:TransformChange(Msg)
    for key, value in ipairs(Msg.positions) do
        positionDict = {}
        for key, value in ipairs(value.position) do
            table.insert(positionDict, value)
        end    

        local player = self.Entitys[value.mail]
        if player ~= nil then
            local motionController = player.RealObject:GetComponent(typeof(MotionController))
            if motionController then
                motionController.movePosition = Vector3.New(positionDict[1], positionDict[2], positionDict[3])
            end
        end
    end
end